import React, { useState, useEffect, useRef } from 'react'
import { Button, PageHeader, Steps, Form, Input, Select, message } from 'antd';
import './News.css'
import axios from 'axios'
import NewsEditor from '../../../components/news-manage/NewsEditor'
const { Option } = Select;
const { Step } = Steps;
export default function NewsUpdate(props) {
    // 当前步骤项
    const [current, setCurrent] = useState(0)
    // 新闻分类列表
    const [categoryList, setCategoryList] = useState([])
    // 表单ref
    const NewsForm = useRef(null)
    // 新闻标题、新闻分类内容
    const [formInfo, setFormInfo] = useState({})
    // 富文本编辑器内容
    const [content, setContent] = useState("")

    // const [newsInfo, setNewsInfo] = useState(null)
    // 获取当前新闻的相关信息
    useEffect(() => {
        axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
            // setNewsInfo(res.data)
            // 解构赋值当前要修改的新闻信息
            let {title,categoryId,content} =res.data
            NewsForm.current.setFieldsValue({
                title:title,
                categoryId:categoryId,
            })
            setContent(content)
        })
    }, [props.match.params.id])

    // 点击下一步
    const handleNext = () => {
        if (current === 0) {
            NewsForm.current.validateFields().then(res => {
                setFormInfo(res)
                setCurrent(current + 1)
            }).catch(error => {
                console.log(error.errorFields[0].errors);
            })
        } else {
            if (content.trim() === "<p></p>" || content.trim() === "") {
                message.error("新闻内容不能为空")
            } else {
                setCurrent(current + 1)
            }
            // console.log(formInfo,content);
        }
    }
    // 点击上一步
    const handlePrevious = () => {
        setCurrent(current - 1)
    }

    // 获取新闻分类数据
    useEffect(() => {
        axios.get("/categories").then(res => {
            setCategoryList(res.data)
        })
    }, [])

    // 获取当前登录用户信息
    // const User=JSON.parse(localStorage.getItem("token"))
    // 保存编辑的草稿箱
    const handleSave = (auditState) => {
        axios.patch(`/news/${props.match.params.id}`, {
            ...formInfo,
            "content": content,
            "auditState": auditState,
        }).then(res=>{
            // 跳转页面
            if(auditState===0){
                props.history.push('/news-manage/draft')
                message.success('您已在草稿箱中成功修改您的新闻')
            }else{
                props.history.push('/audit-manage/list')
                message.success('您可以到审核列表中查看您的新闻')
            }
        })
    }
    return (
        <div>
            {/* 页头 */}
            <PageHeader
                style={{
                    border: '1px solid rgb(235, 237, 240)',
                    backgroundColor: '#ffffff',
                    marginBottom: '30px'
                }}
                onBack={()=>{props.history.goBack()}}
                title="修改新闻"
            />
            {/* 进度条 */}
            <Steps current={current}>
                <Step title="基本信息" description="新闻标题，新闻分类" />
                <Step title="新闻内容" description="新闻主体内容" />
                <Step title="新闻提交" description="保存草稿和提交审核" />
            </Steps>

            {/* 主体内容区 */}
            <div style={{ marginTop: "30px" }}>
                {/* 第一页表单区 */}
                <div className={current === 0 ? '' : 'hidden'}>
                    <Form
                        name="basic"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        initialValues={{ remember: true }}
                        ref={NewsForm}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="新闻标题"
                            name="title"
                            rules={[{ required: true, message: '请输入你的新闻标题' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item label="新闻分类" name="categoryId"
                            rules={[{ required: true, message: '请输入你的新闻分类' }]}>
                            <Select>
                                {
                                    categoryList.map(item => {
                                        return (
                                            <Option value={item.id} key={item.id}>{item.title}</Option>
                                        )
                                    })
                                }
                            </Select>
                        </Form.Item>
                    </Form>
                </div>

            </div>
            {/* 第二页富文本编辑器区 */}
            <div className={current === 1 ? '' : 'hidden'}>
                <NewsEditor getContent={(values) => {
                    setContent(values)
                }} content={content}></NewsEditor>
            </div>
            {/* 第三页 */}
            <div className={current === 2 ? '' : 'hidden'}></div>

            {/* 按钮区域 */}
            <div style={{ marginTop: "50px" }}>
                {/* 处理事件区 */}
                {
                    current === 2 && <span>
                        <Button type="primary"
                            onClick={() => handleSave(0)}>保存草稿箱</Button>
                        <Button danger onClick={() => handleSave(1)}>提交审核</Button>
                    </span>
                }
                {
                    current < 2 && <Button type="primary" onClick={handleNext}>下一步</Button>
                }
                {
                    current > 0 && <Button onClick={handlePrevious}>上一步</Button>
                }

            </div>

        </div>
    )
}
